// pages/scode/scode.js
import {formatDate} from '../../utils/util.js'
import {ApiRootUrl} from '../../config/index.js'
// var config = require('../config/index.js')
var QQMapWX = require('../../libs/qqmap-wx-jssdk.js');
var qqmapsdk;
Page({

  /**
   * 页面的初始数据
   */
  data: {
    companyname: "",
    fitlist:["是","否"],
    date: "",
    companypnum:"",
    isfit:"",
    companyid:"",
    company:"",
    imgsrcnow:"",
    imgsrcsafething:"",
    videosrc:"",

    xlrname:"",//巡防人
    xltime:"",//巡防时间
    xlCompanyname:'',//企业名称
    deadline:'',//截止时间
    address:"",//巡防地址

    imgs: [], // 图片集合 //现场照片 
    uploaderList: [],
    uploaderNum: 0,
    
    imgs2: [], // //安全设施照片
    uploaderList2: [],
    uploaderNum2: 0,
    //
    showUpload: true,
    showUpload2: true,

    longitude: '',
    latitude: '',
  },

  userxlrnameInput(e) {
    this.setData({ xlrname: e.detail.value });
  },
  userxltimeInput(e) {
    this.setData({ xltime: e.detail.value });
  },

  //上传图片相关方法
  // 删除图片
  clearImg: function (e) {
      var nowList = []; //新数据
      var uploaderList = this.data.uploaderList; //原数据
      for (let i = 0; i < uploaderList.length; i++) {
          if (i == e.currentTarget.dataset.index) {
              continue;
          } else {
              nowList.push(uploaderList[i]);
          }
      }
      this.setData({
          uploaderNum: this.data.uploaderNum - 1,
          uploaderList: nowList,
          showUpload: true
      });
      console.log(e);
      //e.currentTarget.dataset.index
      this.data.imgs.splice(e.currentTarget.dataset.index, 1);
      console.log(this.data.imgs);
  },
  //展示图片
  showImg: function (e) {
      var that = this;
      wx.previewImage({
          urls: that.data.uploaderList,
          current: that.data.uploaderList[e.currentTarget.dataset.index]
      });
  },
  //上传图片
  upload: function (e) {

      var that = this;
      wx.chooseImage({
          count: 3 - that.data.uploaderNum, // 默认3
          sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
              console.log(res);
              if (res.tempFiles[0].size > 1048576 * 2) {
                  // console.log('图片太大')
                  wx.showModal({
                      title: "提示",
                      content: "选择的图片过大，请上传不超过2M的图片",
                      showCancel: false,
                      success(res) {
                          if (res.confirm) {
                              //  console.log('用户点击确定')
                          }
                      }
                  });
                  return;
              }
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              let tempFilePaths = res.tempFilePaths;
              let uploaderList = that.data.uploaderList.concat(tempFilePaths);
              if (uploaderList.length == 3) {
                  that.setData({
                      showUpload: false
                  });
              }
              that.setData({
                  uploaderList: uploaderList,
                  uploaderNum: uploaderList.length
              });
              var arr = that.data.imgs;
              if (tempFilePaths.length > 1) {
                  var _n = 0

                  for (var i = 0; i < tempFilePaths.length; i++) {
                      console.log(tempFilePaths)
                      wx.showLoading({
                          title: "图片上传中"
                      });
                      wx.uploadFile({
                          url: ApiRootUrl + "/conf/file/imgUpdate", //仅为示例，非真实的接口地址
                          filePath: tempFilePaths[i],
                          name: "file",
                          formData: {
                              user: "test"
                          },
                          success(res) {
                              _n = _n + 1
                              var o = JSON.parse(res.data);
                              if (_n == tempFilePaths.length) {
                                  wx.hideLoading();
                              }
                              if (o.code == '0000') {
                                  arr.push(o.data);
                              } else {
                                  console.log(that.data.uploaderNum)
                                  console.log(i)
                                  // var _showUpload = that.data.showUpload
                                  var _uploaderNum = that.data.uploaderNum
                                  var _uploaderList = that.data.uploaderList
                                  _uploaderList.splice(i - 1, 1)
                                  console.log(_uploaderList)
                                  that.setData({
                                      uploaderNum: (_uploaderNum == 0) ? 0 : (_uploaderNum - 1),
                                      uploaderList: _uploaderList,
                                      showUpload: _uploaderList.length == 3 ? false : true
                                  });
                                  console.log(_uploaderList)
                                  console.log(_uploaderNum)
                                  // arr = []  arr.splice(1,1)
                                  wx.showModal({
                                      title: '提示信息',
                                      content: '图片上传失败,请重新上传',
                                      showCancel: false
                                  });
                              }
                              that.setData({
                                  imgs: arr
                              });
                              console.log(that.data.imgs);
                          }
                      });
                  }
              }
              else {
                  // wx.showLoading({
                  //     title: "图片上传中"
                  // });
                  // wx.uploadFile({
                  //     url: ApiRootUrl + "/conf/file/imgUpdate", //仅为示例，非真实的接口地址
                  //     filePath: tempFilePaths[0],
                  //     name: "file",
                  //     formData: {
                  //         user: "test"
                  //     },
                  //     success(res) {
                  //         var o = JSON.parse(res.data);
                  //         console.log(tempFilePaths[0])
                  //         if (o.code == '0000') {
                  //             arr.push(o.data);
                  //         } else {
                  //             console.log(that.data.uploaderNum)
                  //             var _uploaderNum = that.data.uploaderNum
                  //             var _uploaderList = that.data.uploaderList
                  //             _uploaderList.pop()
                  //             //console.log(_uploaderList.splice(_uploaderList.length-1, 1),)
                  //             that.setData({
                  //                 uploaderNum: (_uploaderNum == 0) ? 0 : (_uploaderNum - 1),
                  //                 uploaderList: _uploaderList,
                  //                 showUpload: true
                  //                 //uploaderList: arr.splice(1,1); [],
                  //                 //
                  //             });
                  //             //  arr = []
                  //             wx.showModal({
                  //                 title: '提示信息',
                  //                 content: '图片上传失败,请重新上传',
                  //                 showCancel: false
                  //             });
                  //         }
                  //         that.setData({
                  //             imgs: arr
                  //         });
                  //         wx.hideLoading();
                  //         // console.log(e);
                  //         //console.log(o.code);
                  //         console.log(that.data.imgs);
                  //     }
                  // });
              }
          }
      });
  },

  //上传图片相关方法
  // 删除图片
  clearImg2: function (e) {
      var nowList = []; //新数据
      var uploaderList2 = this.data.uploaderList2; //原数据
      for (let i = 0; i < uploaderList2.length; i++) {
          if (i == e.currentTarget.dataset.index) {
              continue;
          } else {
              nowList.push(uploaderList2[i]);
          }
      }
      this.setData({
          uploaderNum2: this.data.uploaderNum2 - 1,
          uploaderList2: nowList,
          showUpload2: true
      });
      console.log(e);
      //e.currentTarget.dataset.index
      this.data.imgs2.splice(e.currentTarget.dataset.index, 1);
      console.log(this.data.imgs2);
  },
  //展示图片
  showImg2: function (e) {
      var that = this;
      wx.previewImage({
          urls: that.data.uploaderList2,
          current: that.data.uploaderList2[e.currentTarget.dataset.index]
      });
  },
  //上传图片
  upload2: function (e) {

      var that = this;
      wx.chooseImage({
          count: 3 - that.data.uploaderNum2, // 默认3
          sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
          sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
          success: function (res) {
              console.log(res);
              if (res.tempFiles[0].size > 1048576 * 2) {
                  // console.log('图片太大')
                  wx.showModal({
                      title: "提示",
                      content: "选择的图片过大，请上传不超过2M的图片",
                      showCancel: false,
                      success(res) {
                          if (res.confirm) {
                              //  console.log('用户点击确定')
                          }
                      }
                  });
                  return;
              }
              // 返回选定照片的本地文件路径列表，tempFilePath可以作为img标签的src属性显示图片
              let tempFilePaths = res.tempFilePaths;
              let uploaderList2 = that.data.uploaderList2.concat(tempFilePaths);
              if (uploaderList2.length == 3) {
                  that.setData({
                      showUpload2: false
                  });
              }
              that.setData({
                  uploaderList2: uploaderList2,
                  uploaderNum2: uploaderList2.length
              });
              var arr = that.data.imgs2;
              if (tempFilePaths.length > 1) {
                  var _n = 0

                  for (var i = 0; i < tempFilePaths.length; i++) {
                      console.log(tempFilePaths)
                      wx.showLoading({
                          title: "图片上传中"
                      });
                      wx.uploadFile({
                          url: ApiRootUrl + "/conf/file/imgUpdate", //仅为示例，非真实的接口地址
                          filePath: tempFilePaths[i],
                          name: "file",
                          formData: {
                              user: "test"
                          },
                          success(res) {
                              _n = _n + 1
                              var o = JSON.parse(res.data);
                              if (_n == tempFilePaths.length) {
                                  wx.hideLoading();
                              }
                              if (o.code == '0000') {
                                  arr.push(o.data);
                              } else {
                                  console.log(that.data.uploaderNum2)
                                  console.log(i)
                                  // var _showUpload2 = that.data.showUpload2
                                  var _uploaderNum2 = that.data.uploaderNum2
                                  var _uploaderList2 = that.data.uploaderList2
                                  _uploaderList2.splice(i - 1, 1)
                                  console.log(_uploaderList2)
                                  that.setData({
                                      uploaderNum2: (_uploaderNum2 == 0) ? 0 : (_uploaderNum2 - 1),
                                      uploaderList2: _uploaderList2,
                                      showUpload2: _uploaderList2.length == 3 ? false : true
                                  });
                                  console.log(_uploaderList2)
                                  console.log(_uploaderNum2)
                                  // arr = []  arr.splice(1,1)
                                  wx.showModal({
                                      title: '提示信息',
                                      content: '图片上传失败,请重新上传',
                                      showCancel: false
                                  });
                              }
                              that.setData({
                                  imgs2: arr
                              });
                              console.log(that.data.imgs2);
                          }
                      });
                  }
              }
              else {
                  // wx.showLoading({
                  //     title: "图片上传中"
                  // });
                  // wx.uploadFile({
                  //     url: ApiRootUrl + "/conf/file/imgUpdate", //仅为示例，非真实的接口地址
                  //     filePath: tempFilePaths[0],
                  //     name: "file",
                  //     formData: {
                  //         user: "test"
                  //     },
                  //     success(res) {
                  //         var o = JSON.parse(res.data);
                  //         console.log(tempFilePaths[0])
                  //         if (o.code == '0000') {
                  //             arr.push(o.data);
                  //         } else {
                  //             console.log(that.data.uploaderNum2)
                  //             var _uploaderNum2 = that.data.uploaderNum2
                  //             var _uploaderList2 = that.data.uploaderList2
                  //             _uploaderList2.pop()
                  //             //console.log(_uploaderList2.splice(_uploaderList2.length-1, 1),)
                  //             that.setData({
                  //                 uploaderNum2: (_uploaderNum2 == 0) ? 0 : (_uploaderNum2 - 1),
                  //                 uploaderList2: _uploaderList2,
                  //                 showUpload2: true
                  //                 //uploaderList2: arr.splice(1,1); [],
                  //                 //
                  //             });
                  //             //  arr = []
                  //             wx.showModal({
                  //                 title: '提示信息',
                  //                 content: '图片上传失败,请重新上传',
                  //                 showCancel: false
                  //             });
                  //         }
                  //         that.setData({
                  //             imgs2: arr
                  //         });
                  //         wx.hideLoading();
                  //         // console.log(e);
                  //         //console.log(o.code);
                  //         console.log(that.data.imgs2);
                  //     }
                  // });
              }
          }
      });
  },







  //上传视频相关方法
  uploadVideo:function(){
    var me =this;
    //微信小程序提供的api，用于选择视频
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      success(res) {
        console.log(res)
        //对视频的长度进行判断，如果小于1s则会提醒用户
        if (duration<1){
          wx.showToast({
            title: '你的视频太短了',
            icon:'none'
          })
          return;
        }else{
          //如果验证通过
          //获得该视频的时间长度
          var duration =res.duration;
          //获得视频的高度
          var height= res.height;
          //获得视频的尺寸
          var size =res.size;
          //获得视频的临时路径
          var tempFilePath =res.tempFilePath;
          //获得视频的宽度
          var width =res.width;


          //获取到上个页面传入的参数，并保存在videoParams
          me.setData({
            videoParams:params
          })

          //上传时候同样需要进行身份认证
          wx.uploadFile({
            url: serverUrl + '/video/uploadVideo', 
            filePath: tempFilePath,
            name: 'file',
            header: {
              'content-type': 'application/json',
            },
            //在uploadFile中如果要传多个数据可以使用formData
            formData:{
              id:user.id,
              videoSeconds: duration,
              videoHeight: height,
              videoWidth: width,
            },
            success(res) {
              console.log(res.data)
              // const data = JSON.parse(res.data);
              wx.hideLoading();
              wx.showToast({
                title: '上传成功',
              })
            }
          })
        }
      }
    })
  },
  //
  //巡逻时间
  bindDateChange: function (e) {
    
    // console.log('picker发送选择改变，携带值为', e.detail.value,formatDate(new Date()))
    this.setData({
      xltime: e.detail.value
    })
  },




  // usercompanyidInput(e) {
  //   this.setData({ companypnum: e.detail.value });
  // },
  // changeDate(e) {
  //   this.setData({ date: e.detail.value });
  // },

  // changeIsfit(e) {
  //   this.setData({ isfit: e.detail.value === "0" ? "是" : "否" });
  // },

  chooseimgnow(e){
    wx.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        console.log(res)
        const images = this.data.imgsrcnow.concat(res.tempFilePaths)
        // 限制最多只能留下3张照片
        // const images1 = images.length <= 1 ? images : images.slice(0, 1)
        this.setData({
          imgsrcnow: res.tempFilePaths
        })
      }
    })
  },

  chooseimgsrcsafething(e) {
    wx.chooseImage({
      sizeType: ['original', 'compressed'],  //可选择原图或压缩后的图片
      sourceType: ['album', 'camera'], //可选择性开放访问相册、相机
      success: res => {
        console.log(res)
        const images = this.data.imgsrcsafething.concat(res.tempFilePaths)
        // 限制最多只能留下3张照片
        // const images1 = images.length <= 1 ? images : images.slice(0, 1)
        this.setData({
          imgsrcsafething: res.tempFilePaths
        })
      }
    })
  },

  choosevideo(e) {
    wx.chooseVideo({
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      camera: 'back',
      success:(res) => {
        console.log(res)
        this.setData({
          videosrc: res.tempFilePath
        })
        
      }
    })
    
  },



  handleImagePreviewnow(e) {
    const idx = e.target.dataset.idx
    const images = this.data.imgsrcnow
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },

  handleImagePreviewsafething(e) {
    const idx = e.target.dataset.idx
    const images = this.data.imgsrcnow
    wx.previewImage({
      current: images[idx],  //当前预览的图片
      urls: images,  //所有要预览的图片
    })
  },

  quit(){
    
    wx.switchTab({
      url: '../qdtj/qdtj'
    })
  },
  submit(){
    
    wx.switchTab({
      url: '../qdtj/qdtj'
    })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    


    var _this =this
    qqmapsdk = new QQMapWX({
      key: '7AHBZ-WSSK3-3IB32-YR6ZX-2MMNE-LUBVJ'
    });
    wx.getLocation({
      success: res => {
        
        _this.setData({
          longitude: res.longitude,
          latitude: res.latitude
        })
        
        qqmapsdk.reverseGeocoder({
          location: {
            longitude: res.longitude,
            latitude: res.latitude
          },
          get_poi: 1,
          poi_options: 'policy=2;radius=3000;page_size=20;page_index=1',
          success: function (addres) {
            _this.setData({
              address:addres.result.address
            })
          },
          fail: function (res) {
            console.log(res);
          },
          complete: function (res) {
            console.log(res);
          }
        });
        
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})